package com.xgry.bpm.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Generator {

    /**
     * RUN THIS
     *
     */
    //生成文件所在项目路径
    private static String baseProjectPath = "/Users/wangguanbo/Documents/IdeaDocument/BPM_REMAKE/";
    private static String[] tables= {"grid_data"};
    private static String  modelname = "griddata";

    //business  base
    private static String dbType = "business";

    //基础包名--生成地址基础库
    private static String basePackage="com.xgry.bpm.api."+dbType;
    //可以设置 table 前缀
    private static String prefix="";

    //数据库配置四要素
    private static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static String url = "jdbc:sqlserver://192.168.1.68:1433;databaseName=BPM2020-MYTEST";
    private static String username = "sa";
    private static String password = "root";


    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(baseProjectPath + "/src/main/java");
        // TODO 设置用户名
        gc.setAuthor("adrian");
        gc.setOpen(true);
        // service 命名方式
        gc.setServiceName("%sService");
        // service impl 命名方式
        gc.setServiceImplName("%sServiceImpl");
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(false);
        mpg.setGlobalConfig(gc);

        // TODO 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        dsc.setDriverName(driverName);
        dsc.setUsername(username);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);

        // TODO 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(basePackage);
        pc.setModuleName(modelname);
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        mpg.setPackageInfo(pc);

        // 自定义需要填充的字段
        //List<TableFill> tableFillList = new ArrayList<>();

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/src/main/resources/mapper/" + modelname
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        focList.add(new FileOutConfig("/templates/service.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String expand = projectPath + "/src/main/java/com/xgry/bpm/api/"+dbType+"/" + modelname + "/" + "service";
                System.out.println("==============");
                System.out.println(tableInfo.getServiceName());
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getServiceName());
                return entityFile;
            }
        });
        focList.add(new FileOutConfig("/templates/serviceImpl.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String expand = projectPath + "/src/main/java/com/xgry/bpm/api/"+dbType+"/" + modelname + "/" + "service/impl";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getServiceImplName());
                return entityFile;
            }
        });

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/controller.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String expand = projectPath + "/src/main/java/com/xgry/bpm/api/"+dbType+"/" + modelname + "/" + "controller";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getControllerName());
                return entityFile;
            }
        });

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/entityForm.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/xgry/bpm/api/" + dbType +"/" + modelname + "/" + "form"
                        + "/" + tableInfo.getEntityName()+"Form" + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/entityVo.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/xgry/bpm/api/" + dbType +"/" + modelname + "/" + "vo"
                        + "/" + tableInfo.getEntityName()+"Vo" + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/entity.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/xgry/bpm/api/" + dbType +"/" + modelname + "/" + "entity"
                        + "/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/mapper.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/xgry/bpm/api/" + dbType +"/" + modelname + "/" + "mapper"
                        + "/" + tableInfo.getEntityName()+"Mapper"+ StringPool.DOT_JAVA;

            }
        });




        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        // 设置逻辑删除键（这个是逻辑删除的操作）
        strategy.setLogicDeleteFieldName("deleted");
        // TODO 指定生成的bean的数据库表名（如果全部生成，这里要注释掉）
        strategy.setInclude(tables);
        //strategy.setSuperEntityColumns("id");
        // 驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
